package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.HealthyArchiveSearchBean;
import com.caifu.enums.LabelTypeEnum;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.service.IStatisticsDataService;
import com.caifu.util.AesMyUtil;
import com.caifu.util.Constance;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;

/**
* 
* 功能描述：养老机构数据统计接口
*
* @Author  GZ
* @Date   2020/11/23 18:31
*/
@Service
public class StatisticsDataServiceImpl implements IStatisticsDataService {

    @Resource
    private YlBedMapper bedMapper;
    @Resource
    private YlBedRecordMapper bedRecordMapper;
    @Resource
    private YlElderlyInfoMapper elderlyInfoMapper;
    @Resource
    private YlBuildingMapper buildingMapper;
    @Resource
    private YlRoomMapper roomMapper;
    @Resource
    private YlFloorMapper floorMapper;
    @Resource
    private YlMonthBillMapper monthBillMapper;
    @Resource
    private UserInfoContactMapper contactMapper;
    @Resource
    private SysOrganizationMapper organizationMapper;
    @Resource
    private YlPensionStatisticMapper pensionStatisticMapper;
    @Resource
    private YlBasicDataMapper basicDataMapper;

    @Override
    public JSONObject queryPensionBasicInfo() throws Exception {
        JSONObject result = new JSONObject();
        int totalPensionCount = 0;
        //查询查询上线的养老机构列表
        QueryWrapper<SysOrganization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("type","4");
        organizationQueryWrapper.eq("state","1");
        organizationQueryWrapper.eq("parent_org_id","1290");
        List<SysOrganization> organizationList =organizationMapper.selectList(organizationQueryWrapper);
        if(null!=organizationList&&organizationList.size()>0){
            totalPensionCount = organizationList.size();
        }
        result.put("organizationList",organizationList);
        result.put("totalPensionCount",totalPensionCount);
        //查询总床位数
        int totalBedCount = bedMapper.queryTotalBedInfoByPensionNo(null,null);
        result.put("totalBedCount",totalBedCount);
        //查询空床位数
        int emptyTotalBed = bedMapper.queryTotalBedInfoByPensionNo(null,"0");
        //查询在住总人数
        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("isStayBack","1");
        int totalPeople = elderlyInfoMapper.getElderlyInfoPageListTotalCount(paraMap);
        result.put("totalPeople",totalPeople);
        //计算入住率
        result.put("occupancy", Constance.toPercent(totalPeople,emptyTotalBed+totalPeople));
        result.put("code","0000");
        result.put("codeDesc","查询信息成功！");
        return result;
    }

    @Override
    public JSONObject queryBedStatisticInfo(String  pensionNo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            //查询总床位数
            int totalBedCount = bedMapper.queryTotalBedInfoByPensionNo(pensionNo,null);
            result.put("totalBedCount",totalBedCount);
            //查询空床位数
            int emptyBedCount = bedMapper.queryTotalBedInfoByPensionNo(pensionNo,"0");
            result.put("emptyBedCount",emptyBedCount);
            //查询入住人数
            Map<String,Object> elderObj = new HashMap<>();
            elderObj.put("pensionNo",pensionNo);
            elderObj.put("isStayBack","1");
            int totalUserCount = elderlyInfoMapper.getElderlyInfoPageListTotalCount(elderObj);
            result.put("totalUserCount",totalUserCount);
            //查询入住率
            result.put("pensionRate",Constance.toPercent(totalUserCount,emptyBedCount+totalUserCount));
            //查询楼苑床位统计信息
            JSONArray buildingArray = new JSONArray();
            int buildingCount = 0;
            QueryWrapper<YlBuilding> buildingQueryWrapper = new QueryWrapper<>();
            buildingQueryWrapper.eq("PENSION_NO",pensionNo);
            buildingQueryWrapper.eq("BUILDING_STATE","1");
            buildingQueryWrapper.orderByDesc("CREATE_TIME");
            List<YlBuilding> buildingList = buildingMapper.selectList(buildingQueryWrapper);
            if(null!=buildingList&&buildingList.size()>0){
                buildingCount = buildingList.size();
                for (YlBuilding b:buildingList
                     ) {
                     if(null!=b){
                         JSONObject obj = new JSONObject();
                         String buildingNo = Constance.Null2EmptyTrim(b.getBuildingNo());
                         obj.put("buildingName",Constance.Null2EmptyTrim(b.getBuildingName()));
                         obj.put("buildingNo",buildingNo);
                         //查询总床位数
                         int emptyBed = bedMapper.queryBedCountByBuildingNo(buildingNo,"0");
                         //查询入住人数
                         Map<String,Object> buildingObj = new HashMap<>();
                         buildingObj.put("buildingNo",buildingNo);
                         buildingObj.put("isStayBack","1");
                         int usedBed = elderlyInfoMapper.getElderlyInfoPageListTotalCount(buildingObj);
                         obj.put("usedBed",usedBed);
                         //查询入住率
                         obj.put("totalBed",emptyBed);
                         buildingArray.add(obj);
                     }
                }
            }
            result.put("buildingCount",buildingCount);
            result.put("buildingInfo",buildingArray);
            result.put("code","0000");
            result.put("codeDesc","查询成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","查询失败！");
            return result;
        }
    }

    @Override
    public JSONObject queryBuildingInfoData(String buildingNo) throws Exception {
        JSONObject result = new JSONObject();
        try {
            //查询楼苑信息
            QueryWrapper<YlBuilding> buildingQueryWrapper = new QueryWrapper<>();
            buildingQueryWrapper.eq("BUILDING_NO",buildingNo);
            YlBuilding building = buildingMapper.selectOne(buildingQueryWrapper);
            if(null==building){
                result.put("code","1001");
                result.put("codeDesc","楼苑信息不存在");
                return result;
            }
            //楼苑名称
            result.put("bName",Constance.Null2EmptyTrim(building.getBuildingName()));
            //楼苑图片
            result.put("bImg",Constance.Null2EmptyTrim(building.getBuildingImg()));
            //查询总床位数
            int totalBed = bedMapper.queryBedCountByBuildingNo(buildingNo,null);
            result.put("totalBed",totalBed);
            //查询空床位数
            int emptyBed = bedMapper.queryBedCountByBuildingNo(buildingNo,"0");
            //查询已入住人数
            //查询入住人数
            Map<String,Object> elderObj = new HashMap<>();
            elderObj.put("buildingNo",building.getBuildingNo());
            elderObj.put("isStayBack","1");
            int usedBed = elderlyInfoMapper.getElderlyInfoPageListTotalCount(elderObj);
            result.put("usedBed",usedBed);
            //查询入住率
            result.put("occupancyRate",Constance.toPercent(usedBed,emptyBed+usedBed));
            //查询楼层信息列表
            JSONArray floorArray = new JSONArray();
            int floorCount = 0;
            QueryWrapper<YlFloor> floorQueryWrapper = new QueryWrapper<>();
            floorQueryWrapper.eq("BUILDING_NO",buildingNo);
            floorQueryWrapper.eq("FLOOR_STATE","1");
            floorQueryWrapper.orderByAsc("CREATE_TIME");
            List<YlFloor> floorListList = floorMapper.selectList(floorQueryWrapper);
            if(null!=floorListList&&floorListList.size()>0){
                floorCount = floorListList.size();
                for (YlFloor f:floorListList
                     ) {
                    if(null!=f){
                        JSONObject obj = new JSONObject();
                        String floorName = Constance.Null2EmptyTrim(f.getFloorName());
                        obj.put("fName",floorName);
                        String floorNo = Constance.Null2EmptyTrim(f.getFloorNo());
                        //查询该楼层入住人数
                        Map<String,Object> floorObj = new HashMap<>();
                        floorObj.put("buildingNo",building.getBuildingNo());
                        floorObj.put("floorNo",floorNo);
                        floorObj.put("isStayBack","1");
                        int fUseBedCount = elderlyInfoMapper.getElderlyInfoPageListTotalCount(floorObj);
                        obj.put("fUseBedCount",fUseBedCount);
                        //查询该楼层空置人数
                        int fEmptyBedCount = bedMapper.queryBedCountByFloorNo(floorNo,"0");
                        obj.put("fEmptyBedCount",fEmptyBedCount);
                        //查询房间信息
                        JSONArray roomArray = new JSONArray();
                        int roomCount = 0;
                        QueryWrapper<YlRoom> roomQueryWrapper = new QueryWrapper<>();
                        roomQueryWrapper.eq("FLOOR_NO",floorNo);
                        roomQueryWrapper.eq("ROOM_STATE","1");
                        roomQueryWrapper.orderByAsc("CREATE_TIME");
                        List<YlRoom> roomList = roomMapper.selectList(roomQueryWrapper);
                        if(null!=roomList&&roomList.size()>0){
                            roomCount = roomList.size();
                            for (YlRoom r: roomList
                                 ) {
                                if(null!=r){
                                    JSONObject roomObj = new JSONObject();
                                    String roomName =Constance.Null2EmptyTrim(r.getRoomName());
                                    roomObj.put("roomName",roomName); //房间名称
                                    String roomType =Constance.Null2EmptyTrim(r.getRoomType());
                                    roomObj.put("roomType",roomType); //房间类型
                                    String roomUser = Constance.Null2EmptyTrim(r.getRoomRemark());
                                    roomObj.put("roomUser",roomUser); //房间用途
                                    String roomNo =Constance.Null2EmptyTrim(r.getRoomNo());
                                    //查询房间信息
                                    JSONArray bedArray = new JSONArray();
                                    int bedCount = 0;
                                    QueryWrapper<YlBed> bedQueryWrapper = new QueryWrapper<>();
                                    bedQueryWrapper.eq("ROOM_NO",roomNo);
                                    bedQueryWrapper.eq("BED_STATE","1");
                                    bedQueryWrapper.orderByAsc("BED_NAME");
                                    List<YlBed> bedList = bedMapper.selectList(bedQueryWrapper);
                                    if(null!=bedList&&bedList.size()>0){
                                        bedCount = bedList.size();
                                        for (YlBed b:bedList
                                             ) {
                                            if(null!=b){
                                                JSONObject bedObj = new JSONObject();
                                                String bedNo = Constance.Null2EmptyTrim(b.getBedNo());
                                                bedObj.put("bedName",b.getBedName());
                                                String isEmpty = Constance.Null2EmptyTrim(b.getBedEmpty());
                                                bedObj.put("isEmpty",isEmpty);
                                                if("1".equals(isEmpty)){
                                                    //查询该床位的老人信息
                                                    Map<String,Object> userMap = elderlyInfoMapper
                                                            .queryElderlyInfoByBedNo(bedNo);
                                                    bedObj.put("userMap",userMap);
                                                }
                                                bedArray.add(bedObj);
                                            }
                                        }
                                        roomObj.put("bedCount",bedCount);
                                        roomObj.put("bedInfo",bedArray);
                                    }
                                    roomArray.add(roomObj);
                                }
                            }
                            obj.put("roomCount",roomCount);
                            obj.put("roomInfo",roomArray);
                        }
                        floorArray.add(obj);
                    }
                }
            }
            result.put("floorCount",floorCount);
            result.put("floorArray",floorArray);
            result.put("code","0000");
            result.put("codeDesc","查询成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","查询失败！");
            return result;
        }
    }

    @Override
    public JSONObject queryOldManBasicStatisticData(String pensionNo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            //查询历史老人数量
            Map<String,Object> totalPara = new HashMap<>();
            totalPara.put("pensionNo",pensionNo);
            int historyOldMan = elderlyInfoMapper.getElderlyInfoPageListTotalCount(totalPara);
            result.put("historyOldMan",historyOldMan);
            //查询目前在住老人总数
            totalPara.put("isStayBack","1");
            int currentOldMan = elderlyInfoMapper.getElderlyInfoPageListTotalCount(totalPara);
            result.put("currentOldMan",currentOldMan);
            //根据性别统计数据信息
            //男性总数
            totalPara.put("userSex","1");
            int manCount =elderlyInfoMapper.getElderlyInfoPageListTotalCount(totalPara);
            result.put("manCount",manCount);
            totalPara.put("userSex","2");
            int woManCount =elderlyInfoMapper.getElderlyInfoPageListTotalCount(totalPara);
            result.put("woManCount",woManCount);
            //根据文化程度获取老人统计信息
            List<Map<String,Object>> eductionData = elderlyInfoMapper
                    .queryElderlyInfoCountByEduction(pensionNo, LabelTypeEnum.WHCD.getKey());
            result.put("eductionData",eductionData);
            //根据社保类型获取老人统计信息
            List<Map<String,Object>> socialInsuranceData = elderlyInfoMapper
                    .queryElderlyInfoCountBySocialInsurance(pensionNo, LabelTypeEnum.SBLX.getKey());
            result.put("socialInsuranceData",socialInsuranceData);
            //根据护理等级获取统计信息
            List<Map<String,Object>> nursingData = elderlyInfoMapper.queryElderlyInfoCountByNursingDegree(pensionNo);
            int maxNursing = 0;
            if(null!=nursingData&&nursingData.size()>0){
                for (Map<String,Object> map:nursingData
                     ) {
                    int count = Constance.Null2EmptyTrimInt(map.get("man_count"));
                    if(count>maxNursing){
                        maxNursing=count;
                    }
                }
            }
            result.put("nursingInterval",getInterval(maxNursing));
            result.put("nursingData",nursingData);
            //根据长护险等级获取统计信息
            List<Map<String,Object>> assessmentData = elderlyInfoMapper.queryElderlyInfoCountByAssessmentDegree(pensionNo);
            int assessmentCount = 0;
            if(null!=assessmentData&&assessmentData.size()>0){
                for (Map<String,Object> map:assessmentData
                ) {
                    int count = Constance.Null2EmptyTrimInt(map.get("man_count"));
                    if(count>assessmentCount){
                        assessmentCount=count;
                    }
                }
            }
            result.put("assessmentInterval",getInterval(assessmentCount));
            result.put("assessmentData",assessmentData);
            //根据年龄和性别获取统计信息
            List<Map<String,Object>> ageOfMan = elderlyInfoMapper.queryElderlyInfoCountByAgeAndSex(pensionNo,"1");
            result.put("ageOfMan",ageOfMan);
            List<Map<String,Object>> ageOfWoman = elderlyInfoMapper.queryElderlyInfoCountByAgeAndSex(pensionNo,"2");
            result.put("ageOfWoman",ageOfWoman);
            result.put("code","0000");
            result.put("codeDesc","查询成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","查询失败！");
            return result;
        }
    }

    @Override
    public JSONObject queryBirthInfo(String pensionNo) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            JSONArray birthArray = new JSONArray();
            JSONArray nextBirthArray = new JSONArray();
            int totalSize = 0;
            int nextBirthSize=0;
            String currentMonth=Constance.simpleDateOne().substring(4,6);
            String nextMonth="";
            if("12".equals(currentMonth)){
                nextMonth="01";
            }else {
                int month = Constance.Null2EmptyTrimInt(currentMonth)+1;
                if(month<10){
                    nextMonth="0"+month;
                }else {
                    nextMonth=""+month;
                }
            }
            //查询当月过生日的老人信息
            List<YlElderlyInfo> userList = elderlyInfoMapper.queryUserInfoListByBirthMonth(currentMonth
                    ,pensionNo,0);
            if(null!=userList&&userList.size()>0){
                totalSize = userList.size();
                for (YlElderlyInfo e:userList
                     ) {
                    if(null!=e){
                        JSONObject obj = new JSONObject();
                        obj.put("userNo",e.getUserNo());
                        obj.put("name",e.getUserName());
                        obj.put("headUrl",e.getImgPath());
                        obj.put("pensionAddress",bedRecordMapper.queryOldUserBedName(e.getUserNo()));
                        String birthDay = Constance.simpleDateFormatOne(e.getBirthDate());
                        obj.put("birth",birthDay.substring(5,10));
                        birthArray.add(obj);
                    }
                }
            }
            //查询下个月过生日的老人信息
            List<YlElderlyInfo> nextUserList = elderlyInfoMapper.queryUserInfoListByBirthMonth(nextMonth
                    ,pensionNo,0);
            if(null!=nextUserList&&nextUserList.size()>0){
                nextBirthSize = nextUserList.size();
                for (YlElderlyInfo e:nextUserList
                ) {
                    if(null!=e){
                        JSONObject nextObj = new JSONObject();
                        nextObj.put("userNo",e.getUserNo());
                        nextObj.put("name",e.getUserName());
                        nextObj.put("headUrl",e.getImgPath());
                        nextObj.put("pensionAddress",bedRecordMapper.queryOldUserBedName(e.getUserNo()));
                        String birthDay = Constance.simpleDateFormatOne(e.getBirthDate());
                        nextObj.put("birth",birthDay.substring(5,10));
                        nextBirthArray.add(nextObj);
                    }
                }
            }
            result.put("code","0000");
            result.put("codeDesc","获取成功");
            result.put("totalSize",totalSize);
            result.put("birthArray",birthArray);
            result.put("nextBirthSize",nextBirthSize);
            result.put("nextBirthArray",nextBirthArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryHealthyArchiveWarningData(String pensionNo, int maxSize) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            HealthyArchiveSearchBean searchBean = new HealthyArchiveSearchBean();
            searchBean.setPensionNo(pensionNo); //养老机构编号
            searchBean.setArchiveFlag("0"); //未建档
            searchBean.setStartCount(0);
            if(maxSize>0){
                searchBean.setEndCount(maxSize);
            }else {
                searchBean.setEndCount(1000);
            }
            int totalSize = 0;
            List<Map<String, Object>> userList = elderlyInfoMapper
                    .pagedQueryElderInfoData(searchBean);
            if(null!=userList&&userList.size()>0){
                totalSize = userList.size();
                for (Map<String, Object> obj: userList
                     ) {
                    if(null!=obj){
                        StringBuffer sb = new StringBuffer();
                        sb.append(obj.get("BUILDING_NAME"));
                        sb.append("-");
                        sb.append(obj.get("ROOM_NAME"));
                        sb.append("-");
                        sb.append(obj.get("BED_NAME"));
                        obj.put("pensionAddress",sb.toString());
                        String inDate = Constance.Null2EmptyTrim(obj.get("CREATE_DATE").toString()).substring(0,10);
                        obj.put("inDate",inDate);
                        //计算健康档案时间
                        String userCreateDate = Constance.disposeDateTime(Constance.Null2EmptyTrim(obj.get("CREATE_DATE")));
                        Long overHour = Constance.obtainHourInfoByDataTime(userCreateDate);
                        obj.put("overHour", overHour);
                    }
                }
            }
            result.put("code","0000");
            result.put("codeDesc","获取成功");
            result.put("totalSize",totalSize);
            result.put("userList",userList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryUserNursingWarningDate(String pensionNo, int maxSize) throws Exception {
        //获取当前时间后一个月的时间
        String nextMonthDate = Constance.getNextDateByMonth(1);
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            int totalSize = 0;
            List<Map<String,Object>> userList = elderlyInfoMapper
                    .queryUserNursingAlertDate(pensionNo,nextMonthDate,maxSize);
            if(null!=userList&&userList.size()>0){
                totalSize = userList.size();
                for (Map<String,Object> obj:userList
                     ) {
                    if(null!=obj){
                        String effectDate = Constance.Null2EmptyTrim(obj.get("EFFECT_DATE"));
                        String userNo = Constance.Null2EmptyTrim(obj.get("USER_NO"));
                        Long effectDateLong = Constance.Null2EmptyTrimLong(effectDate);
                        Long currentDate = Constance.Null2EmptyTrimLong(Constance.simpleDateOne());
                        if(effectDateLong<currentDate){
                            obj.put("redFlag","1");
                        }else {
                            obj.put("redFlag","0");
                        }
                        obj.put("effectDate",Constance.simpleDateFormatOne(effectDate));
                        obj.put("nextEffectDate",Constance.simpleDateFormatOne(obj.get("next_effect_date").toString()));
                        obj.put("pensionAddress",bedRecordMapper.queryOldUserBedName(userNo));
                    }
                }
            }
            result.put("code","0000");
            result.put("codeDesc","获取成功");
            result.put("totalSize",totalSize);
            result.put("userList",userList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryUserAssessmentWarningDate(String pensionNo, int maxSize) throws Exception {
        //获取当前时间后一个月的时间
        String nextMonthDate = Constance.getNextDateByMonth(1);
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            int totalSize = 0;
            List<Map<String,Object>> userList = elderlyInfoMapper
                    .queryUserAssessmentAlertDate(pensionNo,nextMonthDate,maxSize);
            if(null!=userList&&userList.size()>0){
                totalSize = userList.size();
                for (Map<String,Object> obj:userList
                ) {
                    if(null!=obj){
                        String validDate = Constance.Null2EmptyTrim(obj.get("VALID_DATE"));
                        String userNo = Constance.Null2EmptyTrim(obj.get("USER_NO"));
                        Long validDateLong = Constance.Null2EmptyTrimLong(validDate);
                        Long currentDate = Constance.Null2EmptyTrimLong(Constance.simpleDateOne());
                        if(validDateLong<currentDate){
                            obj.put("redFlag","1");
                        }else {
                            obj.put("redFlag","0");
                        }
                        obj.put("validDate",Constance.simpleDateFormatOne(validDate));
                        obj.put("pensionAddress",bedRecordMapper.queryOldUserBedName(userNo));
                    }
                }
            }
            result.put("code","0000");
            result.put("codeDesc","获取成功");
            result.put("totalSize",totalSize);
            result.put("userList",userList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryUserContractWarningDate(String pensionNo, int maxSize) throws Exception {
        //获取当前时间后一个月的时间
        String nextMonthDate = Constance.getNextDateByMonth(1);
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            int totalSize = 0;
            List<Map<String,Object>> userList = elderlyInfoMapper
                    .queryUserContractAlertDate(pensionNo,nextMonthDate,maxSize);
            if(null!=userList&&userList.size()>0){
                totalSize = userList.size();
                for (Map<String,Object> obj:userList
                ) {
                    if(null!=obj){
                        String endDate = Constance.Null2EmptyTrim(obj.get("END_DATE"));
                        String userNo = Constance.Null2EmptyTrim(obj.get("USER_NO"));
                        Long endDateLong = Constance.Null2EmptyTrimLong(endDate);
                        Long currentDate = Constance.Null2EmptyTrimLong(Constance.simpleDateOne());
                        if(endDateLong<currentDate){
                            obj.put("redFlag","1");
                        }else {
                            obj.put("redFlag","0");
                        }
                        obj.put("endDate",Constance.simpleDateFormatOne(endDate));
                        obj.put("pensionAddress",bedRecordMapper.queryOldUserBedName(userNo));
                        //查询紧急联系人信息
                        QueryWrapper<UserInfoContact> contractQueryWrapper = new QueryWrapper<>();
                        contractQueryWrapper.eq("user_no",userNo);
                        List<UserInfoContact> contactList = contactMapper.selectList(contractQueryWrapper);
                        String linkInfo="";
                        if(null!=contactList&&contactList.size()>0){
                            UserInfoContact c = contactList.get(0);
                            if(null!=c){
                                String contactName = Constance.Null2EmptyTrim(c.getContactName());
                                String phoneNumber = "";
                                if(StringUtils.isNotBlank(c.getMobile())){
                                    phoneNumber = AesMyUtil.Decrypt(c.getMobile());
                                }
                                linkInfo= "紧急联系人："+contactName+";"+ phoneNumber;
                            }
                        }
                        obj.put("linkInfo",linkInfo);
                    }
                }
            }
            result.put("code","0000");
            result.put("codeDesc","获取成功");
            result.put("totalSize",totalSize);
            result.put("userList",userList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryBillStatisticDateInfo(String pensionNo,String year,String month) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            //查询总账单信息
            Map<String,Object> billMap = monthBillMapper.queryAllBillInfoByYearAndMonth(pensionNo,year,month);
            result.put("billInfo",billMap);
            //查询总缴费金额
            if(StringUtils.isNotBlank(month)){
                month = year+month;
                year = null;
            }
            String totalPaymentAmount = monthBillMapper.queryTotalPaymentAmount(pensionNo,year,month);
            result.put("totalPaymentAmount",Constance.Null2EmptyTrimDouble(totalPaymentAmount));
            result.put("code","0000");
            result.put("codeDesc","查询成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryPaymentInfoByMonth(String pensionNo,String year,String month) throws Exception {
        //根据月份获取当月的条数
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            int yearInt = Constance.Null2EmptyTrimInt(year);
            int monthInt = Constance.Null2EmptyTrimInt(month);
            int totalDayOfMonth = Constance.getDaysByYearMonth(yearInt,monthInt);
            JSONArray array = new JSONArray();
            Double maxFee=0.0;
            for(int i=1;i<=totalDayOfMonth;i++){
                JSONObject obj = new JSONObject();
                String currentDay ="";
                if(i<10){
                    currentDay="0"+i;
                }else {
                    currentDay=""+i;
                }
                String realMonth = year+month+currentDay;
                obj.put("day",month+"-"+currentDay);
                String dayAmount = monthBillMapper.queryTotalPaymentAmount(pensionNo,null,realMonth);
                Double dayFee = Constance.Null2EmptyTrimDouble(dayAmount);
                if(dayFee>maxFee){
                    maxFee=dayFee;
                }
                obj.put("dayAmount",dayFee);
                array.add(obj);
            }
            result.put("intervalData",getInterval(maxFee));
            result.put("array",array);
            result.put("code","0000");
            result.put("codeDesc","查询成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryPaymentInfoByYear(String pensionNo, String year) throws Exception {
        //根据年份份获取每月缴费金额
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        if(StringUtils.isBlank(pensionNo)){
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            JSONArray array = new JSONArray();
            Double maxFee=0.0;
            for(int i=1;i<=12;i++){
                String month = "";
                if(i<10){
                    month="0"+i;
                }else {
                    month=""+i;
                }
                JSONObject obj = new JSONObject();
                String currentMonth = year+month;
                String monthAmount = monthBillMapper.queryTotalPaymentAmount(pensionNo,null,currentMonth);
                Double monthFee = Constance.Null2EmptyTrimDouble(monthAmount);
                if(monthFee>maxFee){
                    maxFee=monthFee;
                }
                obj.put("month",month);
                obj.put("monthAmount",monthFee);
                array.add(obj);
            }
            result.put("intervalData",getInterval(maxFee));
            result.put("array",array);
            result.put("code","0000");
            result.put("codeDesc","查询成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }

    @Override
    public JSONObject queryOwingPayUserInfo(String pensionNo,int maxSize) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isBlank(pensionNo)){
            result.put("totalSize",0);
            result.put("code","1001");
            result.put("codeDesc","养老机构编号为空");
            return result;
        }
        try {
            //查询欠费人员信息类表
            int totalSize = 0;
            List<Map<String,Object>> mapList = monthBillMapper.queryOwingMoneyUserInfo(pensionNo,maxSize);
            if(null!=mapList&&mapList.size()>0){
                totalSize = mapList.size();
                for (Map<String,Object> map:mapList
                ) {
                    if(null!=map){
                        String userNo =Constance.Null2EmptyTrim(map.get("USER_NO"));
                        map.put("pensionAddress",bedRecordMapper.queryOldUserBedName(userNo));
                        //查询欠费账单的最小日期
                        String dateTime = monthBillMapper.queryMinOwingMoneyBillDate(userNo);
                        String  owningDate=Constance.Null2EmptyTrim(dateTime).substring(0,8);
                        //获取当前日期
                        Long currentDate = Constance.Null2EmptyTrimLong(Constance.simpleDateOne());
                        Long owningDateLong =Constance.Null2EmptyTrimLong(owningDate);
                        String colorFlag= "";
                        Long difference = currentDate-owningDateLong;
                        if(difference<30){
                            colorFlag="1";
                        }else if(difference<90){
                            colorFlag="2";
                        }else {
                            colorFlag="3";
                        }
                        map.put("colorFlag",colorFlag);
                    }
                }
            }
            result.put("totalSize",totalSize);
            result.put("array",mapList);
            result.put("code","0000");
            result.put("codeDesc","查询成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("totalSize",0);
            result.put("code","9999");
            result.put("codeDesc","获取失败");
            return result;
        }
    }
    //获取间个值
    private Map<String,Object> getInterval(double max){
        Map<String,Object> map = new HashMap<>();
        //计算间隔值
        double interval =((int) (max/5)+1);
        map.put("interval",interval);
        map.put("max",interval*5);
        return map;
    }

    @Override
    public List<YlPensionStatistic> queryPensionStatisticInfoByType(String type) throws Exception {
        return pensionStatisticMapper.queryPensionStaticInfo(type);
    }

    @Override
    public JSONObject saveOrUpdateBasicDateInfo(YlBasicData basicData) throws Exception {
        JSONObject result = new JSONObject();
        try {
            if(null!=basicData){
                int hdTotal = 0;
                int hlTotal = 0;
                hdTotal = Constance.Null2EmptyTrimInt(basicData.getAtflyHd())
                        +Constance.Null2EmptyTrimInt(basicData.getFtjlyHd())
                        +Constance.Null2EmptyTrimInt(basicData.getHdsqflyHd())
                        +Constance.Null2EmptyTrimInt(basicData.getLxjlyHd())
                        +Constance.Null2EmptyTrimInt(basicData.getZxczzzhHd());
                hlTotal = Constance.Null2EmptyTrimInt(basicData.getAtflyHl())
                        +Constance.Null2EmptyTrimInt(basicData.getFtjlyHl())
                        +Constance.Null2EmptyTrimInt(basicData.getHdsqflyHl())
                        +Constance.Null2EmptyTrimInt(basicData.getLxjlyHl())
                        +Constance.Null2EmptyTrimInt(basicData.getZxczzzhHl());
                basicData.setHdTotal(hdTotal+"");
                basicData.setHlTotal(hlTotal+"");
                String id = Constance.Null2EmptyTrim(basicData.getId());
                if(StringUtils.isNotBlank(id)){
                    QueryWrapper<YlBasicData> basicDataQueryWrapper = new QueryWrapper<>();
                    basicDataQueryWrapper.eq("id",basicData.getId());
                    basicDataMapper.update(basicData,basicDataQueryWrapper);
                }else {
                    basicDataMapper.insert(basicData);
                }
            }
            result.put("code","0000");
            result.put("codeDesc","设置成功！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code","9999");
            result.put("codeDesc","设置失败！");
            return result;
        }
    }

    @Override
    public YlBasicData queryBasicDataInfo() throws Exception {
        return basicDataMapper.selectOne(null);
    }
}
